﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Common
{
    public class DBConvert
    {

        /// <summary>
        /// 摘要：字符串截取
        /// 创建人：YangGengYuan
        /// 创建日期：2011-10-26
        /// </summary>
        /// <param name="strSouce">字符串源</param>
        /// <param name="iLength">截取长度</param>
        /// <returns>返回截取后的长度</returns>
        public static string CutStr(string strSouce, int iLength)
        {
            if (strSouce.Length > iLength)
                return strSouce.Substring(0, iLength) + "...";
            else
                return strSouce;
        }


        /// <summary>
        /// 摘要：转换成布尔型
        /// 创建人：YangGengYuan
        /// 创建日期：2011-10-26
        /// </summary>
        /// <param name="dbValue">要转换的数据库字段值</param>
        /// <returns>布尔值</returns>
        public static bool ToBool(object dbValue)
        {
            if (dbValue == null || dbValue == DBNull.Value || dbValue.ToString() == string.Empty || dbValue.ToString() == "0")
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将数据库中的日期字段转换为DateTime,如果dbValue为DBNull.Value,则返回DateTime.MinValue;
        /// </summary>
        /// <param name="dbValue">要转换的数据库字段值</param>
        /// <returns>日期</returns>
        public static DateTime ToDateTime(object dbValue)
        {
            if (dbValue == null || dbValue == DBNull.Value || dbValue.ToString() == string.Empty)
            {
                return DateTime.MinValue;
            }
            return Convert.ToDateTime(dbValue);
        }

        /// <summary>
        /// 将日期型转换成数据库字段值，如果time值为time.MinValue，则转换为DBNull.Value
        /// </summary>
        /// <param name="dateTime">要转换的日期</param>
        /// <returns></returns>
        public static Object ToDBValue(DateTime dateTime)
        {
            if (dateTime == DateTime.MinValue)
            {
                return DBNull.Value;
            }

            return dateTime;
        }

        /// <summary>
        /// 将decimal值转成object
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Object ToDBValue(decimal value)
        {
            if (value == decimal.MinValue)
            {
                return DBNull.Value;
            }

            return value;
        }

        /// <summary>
        /// 将double型转换成数据库字段值
        /// </summary>
        /// <param name="d">要转换的日期</param>
        /// <returns></returns>
        public static Object ToDBValue(Double d)
        {
            if (d == Double.MinValue)
            {
                return DBNull.Value;
            }

            return d;
        }

        public static Object ToDBValue(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return DBNull.Value;
            }
            return value;
        }

        public static Object ToDBValue(int d)
        {
            if (d == int.MinValue)
            {
                return DBNull.Value;
            }
            return d;
        }

        /// <summary>
        /// 将整型的数据库字段值转换为System.Int32，如果值为DBNull.Value,则转换为 -1
        /// </summary>
        /// <param name="dbValue">整型的数据库值</param>
        /// <returns></returns>
        public static int ToInt32(object dbValue)
        {
            if (dbValue == null || dbValue == DBNull.Value || dbValue.ToString() == string.Empty)
            {
                return int.MinValue;
            }
            return Convert.ToInt32(dbValue);
        }

        /// <summary>
        ///  将整型的数据库字段值转换为System.Int64，如果值为DBNull.Value,则转换为 -1
        /// </summary>
        /// <param name="dbValue">整型的数据库值</param>
        /// <returns></returns>
        public static Int64 ToInt64(object dbValue)
        {
            if (dbValue == null || dbValue == DBNull.Value)
            {
                return Int64.MinValue;
            }
            return Convert.ToInt64(dbValue);
        }

        /// <summary>
        /// 直接从dataReader中读取第i列的日期值，如果值为空，则返回DateTime.MinValue
        /// </summary>
        /// <param name="dataReader">要从中读取数据的dataReader</param>
        /// <param name="i">dataReader中的列索引</param>
        /// <returns></returns>
        public static DateTime GetDateTime(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? DateTime.MinValue : dataReader.GetDateTime(i);
        }

        /// <summary>
        /// 直接从dataReader中读取字段名为field的值，如果值为空，则返回DateTime.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public static DateTime GetDateTime(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return DateTime.MinValue;
            }

            return (DateTime)dataReader[field];
        }

        public static DateTime? GetDateTimeNullable(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return null;
            }

            return (DateTime)dataReader[field];
        }

        /// <summary>
        /// 直接从dataReader中读取第i列的值,如果值为空，则返回Int.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="i">dataReader中的列索引</param>
        /// <returns></returns>
        public static int GetInt32(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? int.MinValue : dataReader.GetInt32(i);
        }

        /// <summary>
        /// 直接从dataReader中读取第i列的值,如果值为空，则返回Int.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="i">dataReader中的列索引</param>
        /// <returns></returns>
        public static Int64 GetInt64(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? Int64.MinValue : dataReader.GetInt64(i);
        }

        /// <summary>
        /// 直接从dataReader中读取第i列的值,如果值为空，则返回Int.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="i">dataReader中的列索引</param>
        /// <returns></returns>
        public static double GetDouble(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? double.MinValue : dataReader.GetDouble(i);
        }

        public static decimal GetDecimal(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? decimal.MinValue : dataReader.GetDecimal(i);
        }

        public static decimal GetDecimal(DataRow reader, string field)
        {
            if (reader[field] == DBNull.Value)
            {
                return decimal.MinValue;
            }
            return (decimal)reader[field];
        }

        /// <summary>
        /// 直接从dataReader中读取字段名为field的值，如果值为空，则返回Int.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public static int GetInt32(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return int.MinValue;
            }
            return int.Parse(dataReader[field].ToString());
        }

        /// <summary>
        /// 直接从dataReader中读取字段名为field的值，如果值为空，则返回Int64.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public static Int64 GetInt64(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return Int64.MinValue;
            }
            return (Int64)dataReader[field];
        }

        /// <summary>
        /// 直接从dataReader中读取字段名为field的值，如果值为空，则返回double.MinValue
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public static double GetDouble(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return double.MinValue;
            }
            return (double)dataReader[field];
        }

        public static int? GetInt32Nullable(DataRow dataReader, string field)
        {
            if (dataReader[field] == DBNull.Value)
            {
                return null;
            }
            return (int)dataReader[field];
        }

        /// <summary>
        /// 直接从dataReader中读取第i列的值,如果值为空，则返回空串
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="i">dataReader中的列索引</param>
        /// <returns></returns>
        public static string GetString(IDataReader dataReader, int i)
        {
            return dataReader.IsDBNull(i) ? String.Empty : dataReader.GetString(i);
        }

        /// <summary>
        /// 直接从dataReader中读取字段名为field的值，如果值为空，则返回空串
        /// </summary>
        /// <param name="dataReader">要读取数据的dataReader</param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public static string GetString(DataRow dataReader, string field)
        {
            return dataReader[field] == DBNull.Value ? String.Empty : dataReader[field].ToString();
        }

        /// <summary>
        /// 格式化字符串，防注入式攻击
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FormatString(string str)
        {
            return !String.IsNullOrEmpty(str) ? str.Replace("'", String.Empty).Replace("-", String.Empty).Replace(";", String.Empty) : String.Empty;
        }

        public static string GetAnsiStringFixedLength(IDataReader rdr, string field)
        {
            return rdr[field] == DBNull.Value ? null : rdr[field].ToString();
        }

        public static byte[] GetBinary(IDataReader rdr, string field)
        {
            return rdr[field] == DBNull.Value ? null : System.Text.Encoding.UTF8.GetBytes(rdr[field].ToString());
        }

        public static string GetAnsiString(DataRow rdr, string field)
        {
            return rdr[field] == DBNull.Value ? "" : rdr[field].ToString();
        }

        /// <summary>
        /// 创建一个对象实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private T CreateInstance<T>()
        {
            return Activator.CreateInstance<T>();
        }

        /// <summary>
        /// DataTableToList的方法
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<T> DataTableToList<T>(DataTable dt)
        {
            if (dt == null)
            {
                return null;
            }
            if (dt.Rows.Count < 0)
            {
                return null;
            }
            //创建一个泛型集合对象
            IList<T> list = new List<T>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建一个泛型对象
                T t = Activator.CreateInstance<T>();
                PropertyInfo[] propertyInfo = t.GetType().GetProperties();
                foreach (PropertyInfo item in propertyInfo)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (item.Name.ToLower().Equals(dt.Columns[j].ColumnName.ToLower()))
                        {
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                item.SetValue(t, dt.Rows[i][j], null);
                            }
                            else
                            {
                                item.SetValue(t, null, null);
                            }
                            break;
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="i_objlist"></param>
        /// <returns></returns>
        public static DataTable ConvertToDataTable<T>(IList<T> data)
        {
            if (data == null || data.Count <= 0)
            {
                return null;
            }

            DataTable dt = new DataTable(typeof(T).Name);
            DataColumn column;
            DataRow row;

            PropertyInfo[] propertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (T t in data)
            {
                if (t == null)
                {
                    continue;
                }
                row = dt.NewRow();

                foreach (var item in propertyInfo)
                {
                    try
                    {
                        if (dt.Columns[item.Name] == null)
                        {
                            column = new DataColumn(item.Name, item.PropertyType);
                            dt.Columns.Add(column);
                        }
                        row[item.Name] = item.GetValue(t, null);
                    }
                    catch (Exception)
                    {
                        row[item.Name] = item.GetValue("", null);
                        throw;
                    }
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
    }
}
